package com.hz.foodstalls.controller;

import java.util.List;

import com.jfinal.ext.plugin.shiro.ShiroInterceptor;
import org.apache.commons.lang3.StringUtils;

import com.hz.foodstalls.interceptor.AdminInterceptor;
import com.hz.foodstalls.model.Admin;
import com.hz.foodstalls.model.AdminRole;
import com.hz.foodstalls.model.Role;
import com.hz.foodstalls.model.Towns;
import com.hz.foodstalls.model.WechatInfo;
import com.jfinal.aop.Before;
import com.jfinal.ext.kit.Encodes;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;

/**
 * AdminController, Generated by Robot on 2016-9-21 11:15:23.
 */
@Before({AdminInterceptor.class, ShiroInterceptor.class})
@ControllerBind(controllerKey = "/admin", viewPath = "/WEB-INF/views/admin/")
@RequiresRoles(value = { "systemadministrator  "})
public class AdminController extends BaseController {

    private final String MODULE_NAME = "/admin";

    public void index() {
        Page<Admin> page = Admin.dao.page(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10));
        setAttr("page", page);
        render("index.html");
    }

    public void save() {
        Admin model = getModel(Admin.class, "");
        boolean isSave = model.getId() == null;

        if (Admin.dao.saveOrUpdate(model, isSave))
            redirect(MODULE_NAME);
        else
            renderError(501);
    }

    public void roleAssignment() {

        Admin admin = Admin.dao.findById(getParaToInt("id", 0));
        if (admin == null)
            admin = new Admin();
        List<Role> hasroles = Role.dao
                .find("select *from role where id in (select roleSet_id from admin_role where adminSet_id="
                        + admin.getId() + ")");
        Page<Role> page = Role.dao.page(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10));
        setAttr("page", page);
        setAttr("admin", admin);
        setAttr("hasroles", hasroles);
        render("roleAssignment.html");

    }

    public void edit() {
        Admin admin = Admin.dao.findById(getParaToInt("id", 0));
        if (admin == null)
            admin = new Admin();

        setAttr("admin", admin);
        render("edit.html");
    }

    public void delete() {
        String[] adminSetIds = getParaValues("ids");
        StringBuilder success = new StringBuilder();
        StringBuilder error = new StringBuilder();
        for (String adminSetId : adminSetIds) {
            Admin admin = Admin.dao.findById(adminSetId);
            boolean admindelete = Admin.dao.deleteById(adminSetId);
            if (admindelete) {
                List<AdminRole> adminroles = AdminRole.dao.find("select*from admin_role where adminSet_id=?",
                        adminSetId);
                if (adminroles == null || adminroles.isEmpty()) {
                    success.append("用户:[" + admin.getName() + "]删除成功   ");
                } else {
                    for (AdminRole adminRole : adminroles) {
                        Role role = Role.dao.findById(adminRole.getRolesetId());
                        boolean adminroledelete = AdminRole.dao.deleteById(adminRole.getId());
                        if (adminroledelete) {
                            success.append("删除成员[" + admin.getName() + "]以及其绑定角色[" + role.getName() + "]成功");
                        } else {
                            error.append("删除成员[" + admin.getName() + "]以及其绑定角色[" + role.getName() + "]失败");
                        }

                    }

                }

            } else {
                error.append("用户 [" + admin.getName() + "]删除失败 ");
            }
        }
        if (error == null || error.length() == 0) {
            ajaxJsonSuccessMessage(success.toString());
        } else {
            ajaxJsonErrorMessage(error.toString());
        }
    }

    public void update() {
        String id = getPara("id");
        String password = getPara("password");
        if (StringUtils.isBlank(password)) {
            ajaxJsonErrorMessage("密码不能为空！");
        }
        boolean adminupdate = Admin.dao.findById(id).set("password", Encodes.getPwd(password)).update();
        if (adminupdate) {
            ajaxJsonSuccessMessage("修改成功");
        } else {
            ajaxJsonErrorMessage("修改失败");
        }

    }

    public void townsAdminister() {
        Admin admin = Admin.dao.findById(getParaToInt("id", 0));
        if (admin == null)
            admin = new Admin();
        List<Towns> page = Towns.dao.find("select * from towns");
        setAttr("page", page);
        setAttr("admin", admin);
        setAttr("hastowns", admin.getAreaId());
        render("townsAdminister.html");

    }

    public void wxAdminister() {
        Admin admin = Admin.dao.findById(getParaToInt("id", 0));
        if (admin == null)
            admin = new Admin();
        List page = WechatInfo.dao.find("select * from wechat_info");
        setAttr("page", page);
        setAttr("admin", admin);
        setAttr("haswx", admin.getWxId());
        render("wxAdminister.html");

    }

    public void savetowns() {
        boolean isSave = true;
        boolean success = false;
        int id = Integer.valueOf(getPara("adminId"));
        String[] townsIds = getParaValues("ids[]");
        String towns = null;
        Admin admin = Admin.dao.findById(id);
        if (townsIds != null) {
            if (townsIds.length > 1) {
                towns = townsIds[0];
                for (int i = 1; i < townsIds.length; i++) {
                    towns = towns + "," + townsIds[i];
                }
            } else {
                towns = townsIds[0];
            }
            admin.setAreaId(towns);
            success = Admin.dao.saveOrUpdate(admin, isSave);

        } else {
            towns = "";
            admin.setAreaId(towns);
            success = Admin.dao.saveOrUpdate(admin, isSave);
        }
        if (success) {
            ajaxJsonSuccessMessage("保存成功");
        } else {
            renderError(501);
        }
    }

    public void savewx() {
        boolean isSave = true;
        boolean success = false;
        int id = Integer.valueOf(getPara("adminId"));
        String[] wxIds = getParaValues("ids[]");
        String wx = null;
        Admin admin = Admin.dao.findById(id);
        if (wxIds != null) {
            if (wxIds.length > 1) {
                wx = wxIds[0];
                for (int i = 1; i < wxIds.length; i++) {
                    wx = wx + "," + wxIds[i];
                }
            } else {
                wx = wxIds[0];
            }
            admin.setWxId(wx);
            success = Admin.dao.saveOrUpdate(admin, isSave);

        } else {
            wx = "";
            admin.setWxId(wx);
            success = Admin.dao.saveOrUpdate(admin, isSave);
        }
        if (success) {
            ajaxJsonSuccessMessage("保存成功");
        } else {
            renderError(501);
        }
    }

    public void updatePwd() {
        String username = getSessionAttr("username");
        Admin admin = Admin.dao.findFirst("select * from admin where username = ?", username);
        int id = admin.getId();
        String password = getPara("password");
        if (StringUtils.isBlank(password)) {
            ajaxJsonErrorMessage("密码不能为空！");
        }
        boolean adminupdate = Admin.dao.findById(id).set("password", Encodes.getPwd(password)).update();
        if (adminupdate) {
            ajaxJsonSuccessMessage("修改成功");
        } else {
            ajaxJsonErrorMessage("修改失败");
        }

    }
}
